package top.chukongxiang.project.base.controller.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import top.chukongxiang.project.base.model.entity.sys.Menu;
import top.chukongxiang.project.base.model.entity.user.User;
import top.chukongxiang.project.base.model.response.R;
import top.chukongxiang.project.base.model.vo.KeywordsPageVo;
import top.chukongxiang.project.base.model.vo.sys.MenuTreeVo;
import top.chukongxiang.project.base.model.vo.user.UserVo;
import top.chukongxiang.project.base.oauth2.UserInfo;
import top.chukongxiang.project.base.service.user.UserService;
import top.chukongxiang.project.base.utils.TreeUtils;

import java.util.List;
import java.util.Objects;

/**
 * 用户基础相关
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/11 4:02
 */
@RestController
@RequestMapping("user")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return 响应
     */
    @Deprecated
    @GetMapping("{username}")
    public R<User> getInfoById(@PathVariable String username) {
        return R.ok(userService.getUserInfoByUsername(username));
    }

    /**
     * 获取当前用户的菜单
     * @param userInfo
     * @return
     */
    @GetMapping("menu")
    public R<List<MenuTreeVo>> currentMenus(@AuthenticationPrincipal UserInfo userInfo) {
        List<Menu> menus = userService.listMenuByUserId(userInfo.getUserId());
        List<MenuTreeVo> menuTreeVos = TreeUtils.parseTree(menus, MenuTreeVo.class, MenuTreeVo::getId, MenuTreeVo::getParentId, MenuTreeVo::getChildren, MenuTreeVo::setChildren, Objects::deepEquals, null);
        return R.ok(menuTreeVos);
    }

    /**
     * 根据关键字分页查询
     * @param keywordsPageVo
     * @return
     */
    @PostMapping("page")
    public R<IPage<UserVo>> list(@RequestBody KeywordsPageVo<User> keywordsPageVo) {
        IPage<UserVo> page = userService.pageUser(keywordsPageVo);
        return R.ok(page);
    }

    /**
     * 根据角色id分页查询用户
     * @param keywordsPageVo
     * @return
     */
    @PostMapping("page-by-role")
    public R<?> listByRole(@RequestBody KeywordsPageVo<User> keywordsPageVo) {
        IPage<? extends User> pageUsers
                = userService.pageUserByRoleId(keywordsPageVo);
        return R.ok(pageUsers);
    }
}
